//
//  ConversionBox.swift
//  DatePickerView
//
//  Created by 蓓蕾 on 2022/3/24.
//字符串与数组、字典相互转换

import UIKit

class ConversionBox: NSObject {
    
    /// 字符串转数组
    class func stringConversionToArray(_ str: String) -> Array<Any>?{
        let data = str.data(using: String.Encoding.utf8)
        if let array = try? JSONSerialization.jsonObject(with: data!,
                                                        options: .mutableContainers) as? Array<Any> {
            return array
        }
        return nil
    }
    
    /// 字符串转字典
    class func stringConversionToDictionary(_ str: String) -> [String : Any]?{
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!,
                        options: .mutableContainers) as? [String : Any] {
            return dict
        }
        return nil
    }
    
    /// 数组转换为JSONString
    class func getJSONStringFromArray(array:NSArray) -> String {
        if (!JSONSerialization.isValidJSONObject(array)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
         
    }
    
    /**
     字典转换为JSONString
     - parameter dictionary: 字典参数
     - returns: JSONString
     */
    class func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }

}
